import uuid
import winrm
from smbprotocol.connection import Connection
from smbprotocol.session import Session
from smbprotocol.tree import TreeConnect
from smbprotocol.open import Open
import paramiko

def _smbprotocol(server_data):
    server_ip = server_data['server_ip']
    port = server_data['port']
    username = server_data['username']
    password = server_data['password']

    # 连接到服务器
    connection = Connection(uuid.uuid4(), server_ip, port)
    connection.connect()

    # 创建会话
    session = Session(connection, username=username, password=password)
    session.connect()

    # 连接到共享
    tree = TreeConnect(session, r"\\server_ip\share_name")
    tree.connect()

    # 打开远程文件
    file = Open(tree, "file_to_download.txt")
    # 读取文件内容
    file_content = file.read(0, file.end_of_file)

    # 保存到本地
    with open("downloaded_file.txt", "wb") as f:
        f.write(file_content)

    # 关闭文件和连接
    file.close()
    tree.disconnect()
    session.disconnect()
    connection.disconnect()


def _pywinrm():
    # 使用 WinRM 连接
    session = winrm.Session('http://server_ip:5985/wsman', auth=('your_username', 'your_password'))

    # 运行 PowerShell 命令来下载文件
    ps_script = r'''
       $source = "\\server_ip\share_name\file_to_download.txt"
       $destination = "C:\local_path\downloaded_file.txt"
       Copy-Item -Path $source -Destination $destination
       '''
    result = session.run_ps(ps_script)


def _ftp():
    from ftplib import FTP

    # 连接到 FTP 服务器
    ftp = FTP('server_ip')
    ftp.login(user='your_username', passwd='your_password')

    # 切换到指定目录
    ftp.cwd('/path/to/file')

    # 下载文件
    with open('downloaded_file.txt', 'wb') as f:
        ftp.retrbinary('RETR file_to_download.txt', f.write)

    # 断开连接
    ftp.quit()


def by_paramiko_download_file(host, port, username, password, remote_file, local_file):

    ssh = paramiko.SSHClient()
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    ssh.connect(host, port=port, username=username, password=password)
    sftp = ssh.open_sftp()
    sftp.get(remote_file, local_file)
    sftp.close()
    ssh.close()